package com.program.facesigninsystem.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.program.facesigninsystem.api.CommonPage;
import com.program.facesigninsystem.dao.AuthorityDao;
import com.program.facesigninsystem.dao.IAdminGroupDao;
import com.program.facesigninsystem.entity.AdminGroup;
import com.program.facesigninsystem.iteration.dto.LowerApplyRecord;
import com.program.facesigninsystem.iteration.dto.OwnApplyHistory;
import com.program.facesigninsystem.iteration.dto.OwnAuth;
import com.program.facesigninsystem.iteration.dto.RecordDetail;
import com.program.facesigninsystem.iteration.entity.AdminGroupEntity;
import com.program.facesigninsystem.iteration.entity.ApplyRecordEntity;
import com.program.facesigninsystem.iteration.entity.UserEntity;
import com.program.facesigninsystem.iteration.mapper.AdminGroupMapper;
import com.program.facesigninsystem.iteration.mapper.ApplyRecordMapper;
import com.program.facesigninsystem.iteration.mapper.UserMapper;
import com.program.facesigninsystem.service.AuthorityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AuthorityServiceImpl implements AuthorityService {

    @Resource
    ApplyRecordMapper applyRecordMapper;
    @Resource
    AdminGroupMapper adminGroupMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    AuthorityDao authorityDao;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private IAdminGroupDao iAdminGroupDao;

    @Override
    public OwnAuth getOwnAuth(String uid) {

        UserEntity userEntity = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("uid", uid));
        if (userEntity.getAdminGroupId() != null) {

            OwnAuth ownAuth = new OwnAuth();
            AdminGroupEntity adminGroupEntity = adminGroupMapper.selectById(userEntity.getAdminGroupId());
            ownAuth.setAdminGroupEntity(adminGroupEntity);
            if (adminGroupEntity.getWhetherBind() == 1) {
                AdminGroupEntity fatherAdminGroupEntity = adminGroupMapper.selectById(adminGroupEntity.getFatherGroupId());
                ownAuth.setFatherLevel(fatherAdminGroupEntity.getGroupLevel())
                        .setFatherName(fatherAdminGroupEntity.getGroupName())
                        .setWhetherSeeAttendance(adminGroupEntity.getWhetherSeeAttendance());
            }
            return ownAuth;
        }
        return null;
    }

    @Override
    public List<AdminGroupEntity> getGroupList(int groupLevel, int groupId) {

        if (groupLevel == 1)
            return adminGroupMapper.selectList(new QueryWrapper<AdminGroupEntity>().eq("group_level", groupLevel).eq("whether_audit", 1));
        else
            return adminGroupMapper.selectList(new QueryWrapper<AdminGroupEntity>().eq("father_group_id", groupId).eq("whether_audit", 1));
    }
    @Override
    public List<AdminGroupEntity> getGroupList1(int groupLevel) {
            return adminGroupMapper.selectList(new QueryWrapper<AdminGroupEntity>().eq("group_level", groupLevel).eq("whether_audit", 1));
    }
    @Override
    public List<String> getsuperiors(int groupId){
        List<String> list=new ArrayList<>();
        int fatherid= iAdminGroupDao.selectfathergroupid(groupId);
        while(fatherid!=0){
            List<Map<String, Object>> result=iAdminGroupDao.selectbyid(fatherid);
            for (Map<String, Object> map : result) {
                list.add((String)map.get("group_name"));
            }
            fatherid= iAdminGroupDao.selectfathergroupid(fatherid);
        }
        return list;

    }

    @Override
    public Boolean subAuthApply(String uid, int groupId, String groupName) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {

            //新建组织
            AdminGroupEntity adminGroupEntity = new AdminGroupEntity();
            if (groupId == 0) {
                if (adminGroupMapper.selectOne(new QueryWrapper<AdminGroupEntity>().eq("group_name", groupName)) != null)
                    return false;
                adminGroupEntity.setGroupName(groupName)
                        .setGroupLevel(1)
                        .setFatherGroupId(0)
                        .setWhetherAudit(0)
                        .setWhetherBind(1)
                        .setWhetherSeeAttendance(1);
            } else {
                adminGroupEntity.setGroupName(groupName)
                        .setGroupLevel(adminGroupMapper.selectById(groupId).getGroupLevel() + 1)
                        .setFatherGroupId(groupId)
                        .setWhetherAudit(0)
                        .setWhetherBind(1)
                        .setWhetherSeeAttendance(1);
            }
            adminGroupMapper.insert(adminGroupEntity);

            //插入申请记录
            ApplyRecordEntity applyRecord = new ApplyRecordEntity();
            applyRecord.setApplyUid(uid)
                    .setApplyType(1)
                    .setApplyTime(new Date())
                    .setApplyGroupId(adminGroupEntity.getId())
                    .setStatus(0);

            applyRecordMapper.insert(applyRecord);

            //提交事务
            platformTransactionManager.commit(status);
            return true;
        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }

    @Override
    public Boolean subAuthApply1(String uid, int groupLevel, String groupName){
        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {

            //新建组织
            AdminGroupEntity adminGroupEntity = new AdminGroupEntity();
            if (adminGroupMapper.selectOne(new QueryWrapper<AdminGroupEntity>().eq("group_name", groupName)) != null)
                return false;
            adminGroupEntity.setGroupName(groupName)
                    .setGroupLevel(groupLevel)
                    .setFatherGroupId(0)
                    .setWhetherAudit(0)
                    .setWhetherBind(1)
                    .setWhetherSeeAttendance(1);
            adminGroupMapper.insert(adminGroupEntity);

            //插入申请记录
            ApplyRecordEntity applyRecord = new ApplyRecordEntity();
            applyRecord.setApplyUid(uid)
                    .setApplyType(1)
                    .setApplyTime(new Date())
                    .setApplyGroupId(adminGroupEntity.getId())
                    .setStatus(0);

            applyRecordMapper.insert(applyRecord);

            //提交事务
            platformTransactionManager.commit(status);
            return true;
        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }
    @Override
    public CommonPage<OwnApplyHistory> getAuthApplyHistory(String uid, int pageNum, int pageSize) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            List<OwnApplyHistory> applyHistoryList = new ArrayList<>();

            //分页
            PageHelper.startPage(pageNum, pageSize);
            List<ApplyRecordEntity> applyRecordEntityList = applyRecordMapper.selectList(new QueryWrapper<ApplyRecordEntity>()
                    .eq("apply_uid", uid)
                    .eq("apply_type", 1));
            CommonPage<ApplyRecordEntity> applyRecordEntityCommonPage = CommonPage.restPage(applyRecordEntityList);

            for (ApplyRecordEntity applyRecordEntity : applyRecordEntityList) {

                OwnApplyHistory applyHistory = new OwnApplyHistory();
                AdminGroupEntity adminGroupEntity = adminGroupMapper.selectById(applyRecordEntity.getApplyGroupId());

                applyHistory.setRecordId(applyRecordEntity.getId())
                        .setGroupId(applyRecordEntity.getApplyGroupId())
                        .setGroupName(adminGroupEntity.getGroupName())
                        .setApplyTime(applyRecordEntity.getApplyTime())
                        .setStatus(applyRecordEntity.getStatus());
                applyHistoryList.add(applyHistory);
            }

            //提交事务
            platformTransactionManager.commit(status);
            return CommonPage.restPage2(applyRecordEntityCommonPage, applyHistoryList);

        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return null;
        }
    }

    @Override
    public RecordDetail getOneAuthApplyDetail(int recordId) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            RecordDetail recordDetail = new RecordDetail();
            ApplyRecordEntity applyRecordEntity = applyRecordMapper.selectById(recordId);

            //寻找被申请组织的上级组织
            Integer fatherGroupId = adminGroupMapper.selectById(applyRecordEntity.getApplyGroupId()).getFatherGroupId();
            if (fatherGroupId == 0) {
                recordDetail.setAuditGroup("系统管理员")
                        .setStatus(applyRecordEntity.getStatus())
                        .setAuditTime(applyRecordEntity.getAuditTime())
                        .setRejectReason(applyRecordEntity.getRejectReason());
            } else {
                recordDetail.setAuditGroup(adminGroupMapper.selectById(fatherGroupId).getGroupName())
                        .setStatus(applyRecordEntity.getStatus())
                        .setAuditTime(applyRecordEntity.getAuditTime())
                        .setRejectReason(applyRecordEntity.getRejectReason());
            }

            //提交事务
            platformTransactionManager.commit(status);
            return recordDetail;

        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return null;
        }
    }

    @Override
    public List<LowerApplyRecord> getAuthApplyRecord(String uid, int pageNum, int pageSize) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            //分页
            PageHelper.startPage(pageNum, pageSize);
            List<LowerApplyRecord> lowerApplyRecordList = new ArrayList<>();
            if (uid.equals("0")) {
                lowerApplyRecordList = authorityDao.selectAuthRecord(0);
            } else {
                UserEntity userEntity = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("uid", uid));
                lowerApplyRecordList = authorityDao.selectAuthRecord(userEntity.getAdminGroupId());
            }

            //提交事务
            platformTransactionManager.commit(status);
            return lowerApplyRecordList;

        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return null;
        }
    }

    @Override
    public List<LowerApplyRecord> getBind(String uid, int pageNum, int pageSize) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            //分页
            PageHelper.startPage(pageNum, pageSize);
            List<LowerApplyRecord> lowerApplyRecordList = new ArrayList<>();
            if (uid.equals("0")) {
                lowerApplyRecordList = authorityDao.selectAuthRecord1(0);
            } else {
                UserEntity userEntity = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("uid", uid));
                lowerApplyRecordList = authorityDao.selectAuthRecord1(userEntity.getAdminGroupId());
            }

            //提交事务
            platformTransactionManager.commit(status);
            return lowerApplyRecordList;

        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return null;
        }
    }
    @Override
    public CommonPage<OwnApplyHistory> getBindApplyHistory(String uid, int pageNum, int pageSize) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {

            //分页
            PageHelper.startPage(pageNum, pageSize);
            List<OwnApplyHistory> applyHistoryList = new ArrayList<>();
            List<ApplyRecordEntity> applyRecordEntityList = applyRecordMapper.selectList(new QueryWrapper<ApplyRecordEntity>()
                    .eq("apply_uid", uid));

            CommonPage<ApplyRecordEntity> applyRecordEntityCommonPage = CommonPage.restPage(applyRecordEntityList);
            for (ApplyRecordEntity applyRecordEntity : applyRecordEntityList) {

                OwnApplyHistory applyHistory = new OwnApplyHistory();
                AdminGroupEntity adminGroupEntity = adminGroupMapper.selectById(applyRecordEntity.getApplyGroupId());

                applyHistory.setRecordId(applyRecordEntity.getId())
                        .setGroupId(applyRecordEntity.getApplyGroupId())
                        .setGroupName(adminGroupEntity.getGroupName())
                        .setApplyTime(applyRecordEntity.getApplyTime())
                        .setStatus(applyRecordEntity.getStatus());
                applyHistoryList.add(applyHistory);
            }

            //提交事务
            platformTransactionManager.commit(status);
            return CommonPage.restPage2(applyRecordEntityCommonPage, applyHistoryList);

        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return null;
        }
    }

    @Override
    public Boolean subBindApply(String uid, int groupId) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            ApplyRecordEntity applyRecord = new ApplyRecordEntity();
            applyRecord.setApplyUid(uid)
                    .setApplyType(2)
                    .setApplyTime(new Date())
                    .setApplyGroupId(groupId)
                    .setStatus(0);

            applyRecordMapper.insert(applyRecord);

            //提交事务
            platformTransactionManager.commit(status);
            return true;
        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }

    @Override
    public List<LowerApplyRecord> getBindApplyRecord(int groupId, int pageNum, int pageSize) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            //分页
            PageHelper.startPage(pageNum, pageSize);
            List<LowerApplyRecord> lowerApplyRecordList = authorityDao.selectBindRecord(groupId);

            //提交事务
            platformTransactionManager.commit(status);
            return lowerApplyRecordList;

        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return null;
        }
    }

    @Override
    public Boolean handleApply(int applyRecordId, int applyType, int handleType, String rejectReason) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            ApplyRecordEntity applyRecordEntity = applyRecordMapper.selectById(applyRecordId);

            //同意
            if (handleType == 1) {

                //权限申请
                if (applyType == 1) {
                    //将组织变为可用
                    AdminGroupEntity adminGroupEntity = adminGroupMapper.selectById(applyRecordEntity.getApplyGroupId());
                    adminGroupEntity.setWhetherAudit(1);
                    adminGroupEntity.setWhetherBind(1);
                    adminGroupMapper.updateById(adminGroupEntity);

                    //为用户加权限
                    UserEntity userEntity = userMapper.selectOne(new QueryWrapper<UserEntity>()
                            .eq("uid", applyRecordEntity.getApplyUid()));
                    userEntity.setRoleid(adminGroupEntity.getGroupLevel()).setAdminGroupId(applyRecordEntity.getApplyGroupId());
                    userMapper.update(userEntity, new QueryWrapper<UserEntity>()
                            .eq("uid", applyRecordEntity.getApplyUid()));
                }

                //绑定申请
                if (applyType == 2) {
                    UserEntity userEntity = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("uid", applyRecordEntity.getApplyUid()));
                    AdminGroupEntity adminGroupEntity = adminGroupMapper.selectById(userEntity.getAdminGroupId());
                    adminGroupEntity.setFatherGroupId(applyRecordEntity.getApplyGroupId())
                            .setWhetherBind(1);
                    adminGroupMapper.updateById(adminGroupEntity);
                }

                applyRecordEntity.setStatus(1);

            } else {
                applyRecordEntity.setStatus(2);
            }

            //更新记录
            applyRecordEntity.setAuditTime(new Date())
                    .setRejectReason(rejectReason);
            applyRecordMapper.updateById(applyRecordEntity);

            //提交事务
            platformTransactionManager.commit(status);
            return true;

        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }

    @Override
    public Boolean cancelBind(String bindUid, int groupId) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            //用户失去单位
//            UserEntity userEntity = userMapper.selectById(bindUid);
//            userEntity.setAdminGroupId(0);
//            userMapper.updateById(userEntity);

            AdminGroupEntity adminGroupEntity = adminGroupMapper.selectById(groupId);
            //记录改为已解绑
            ApplyRecordEntity applyRecordEntity = applyRecordMapper.selectOne(new QueryWrapper<ApplyRecordEntity>()
                    .eq("apply_uid", bindUid)
                    .eq("apply_group_id", adminGroupEntity.getId())
                    .eq("status", 1));
            applyRecordEntity.setStatus(3);
            applyRecordMapper.updateById(applyRecordEntity);

            //不失去父单位，改为未绑定
//            adminGroupEntity.setFatherGroupId(0);
            adminGroupEntity.setWhetherBind(0);
            adminGroupMapper.updateById(adminGroupEntity);

            //提交事务
            platformTransactionManager.commit(status);
            return true;

        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }

    @Override
    public Boolean cancelBind1(String bindUid, int groupId) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            //用户失去单位
//            UserEntity userEntity = userMapper.selectById(bindUid);
//            userEntity.setAdminGroupId(0);
//            userMapper.updateById(userEntity);

            AdminGroupEntity adminGroupEntity = adminGroupMapper.selectById(groupId);
            //记录改为已解绑
            ApplyRecordEntity applyRecordEntity = applyRecordMapper.selectOne(new QueryWrapper<ApplyRecordEntity>()
                    .eq("apply_uid", bindUid)
                    .eq("apply_group_id", adminGroupEntity.getId())
                    .eq("status", 1));
            applyRecordEntity.setStatus(1);
            applyRecordMapper.updateById(applyRecordEntity);

            //不失去父单位，改为未绑定
//            adminGroupEntity.setFatherGroupId(0);
            adminGroupEntity.setWhetherBind(1);
            adminGroupMapper.updateById(adminGroupEntity);

            //提交事务
            platformTransactionManager.commit(status);
            return true;

        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }
    @Override
    public Boolean changeAttendanceStatus(int groupId, int whetherSeeAttendance) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            AdminGroupEntity adminGroupEntity = adminGroupMapper.selectById(groupId);
            if (adminGroupEntity.getWhetherSeeAttendance() == 0)
                adminGroupEntity.setWhetherSeeAttendance(1);
            else
                adminGroupEntity.setWhetherSeeAttendance(0);
            adminGroupMapper.updateById(adminGroupEntity);

            //提交事务
            platformTransactionManager.commit(status);
            return true;

        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }

    @Override
    public Boolean bindTeacher(String uid, String university, String academy, String major, String job_number, int whetherSeeAttendance) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            UserEntity userEntity = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("uid", uid));
            userEntity.setUniversity(university)
                    .setAcademy(academy)
                    .setMajor(major)
                    .setJobNumber(job_number)
                    .setWhetherSeeAttendance(whetherSeeAttendance);
            userMapper.update(userEntity, new QueryWrapper<UserEntity>().eq("uid", uid));

            //提交事务
            platformTransactionManager.commit(status);
            return true;

        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }
}
